package com.gj.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: xiaobin
 * @create: 2020-12-14 23:58
 */
public class DlhFrameDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        Object decoded = decode(ctx, in);
        if (decoded != null) {
            out.add(decoded);
        }
    }

    private Object decode(ChannelHandlerContext ctx, ByteBuf in) {

//        byte aByte = in.getByte(0);
//        System.out.println(aByte);
//
//        byte aa = (byte) 0xaa;
//
//        System.out.println(aa == aByte);

        List<Byte> list = new ArrayList<>();
        for (int i = 0; i < in.writerIndex(); i ++) {
            list.add(in.getByte(i));
//            System.out.println(i);
//            System.out.println(intTohex(in.getByte(i)));
        }

        for (byte i : list) {
            System.out.println(i);
//            System.out.println(Integer.);
        }

//
//        byte aa = (byte) 0xAA;
//        int index = indexOf(in, aa);
//        if(index != -1){
//            if (in.readableBytes() < index) {
//                return null;
//            }
//            return in.readSlice(index).retain();
//        }
        return null;
    }

    //数据和
    public static byte  getDataAdd(byte[] bs){
        byte he = 0;
        if(bs != null){
            for (int i = 0; i < bs.length; i++) {
                he += bs[i];
            }
        }
        return he;
    }


    /**
     * Returns the number of bytes between the readerIndex of the haystack and
     * the first needle found in the haystack.  -1 is returned if no needle is
     * found in the haystack.
     */
    private static int indexOf(ByteBuf haystack, byte b) {
        for (int i = 0; i < haystack.writerIndex(); i ++) {
            if(haystack.getByte(i) == b){
                int index = i+haystack.getByte(i+1)+3;
                int he = haystack.getByte(index-1);
                byte[] hh = new byte[index-i-2];
                haystack.getBytes(i+1, hh, 0, hh.length);
                if(he == getDataAdd(hh)){
                    return index;
                }
            }
        }
        return -1;
    }

    public static String intTohex(int n) {
        StringBuffer s = new StringBuffer();
        String a;
        char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        while (n != 0) {
            s = s.append(b[n % 16]);
            n = n / 16;
        }
        a = s.reverse().toString();
        if ("".equals(a)) {
            a = "00";
        }
        if (a.length() == 1) {
            a = "0" + a;
        }
        return a;
    }

}
